package com.wang.systemsettings

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import android.provider.Settings;


class MainActivity : ComponentActivity() {

    private var btnSettings: Button? = null
    private var btnApps: Button? = null
    private var btnMegaEngineeringMode: Button? = null

    private val targetPackageName = "com.mega.app.engineeringmode"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main);
        btnSettings = findViewById(R.id.btnSettings);
        btnApps = findViewById(R.id.btnApps);
        btnMegaEngineeringMode = findViewById(R.id.btnMegaEngineeringMode);
        // 设置点击事件
        setupClickListeners();
    }

    private fun setupClickListeners() {
        // 按钮1: 打开系统设置
        btnSettings!!.setOnClickListener(View.OnClickListener { v: View? ->
            val intent: Intent = Intent(Settings.ACTION_SETTINGS)
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent)
            } else {
                Toast.makeText(this, "无法打开系统设置", Toast.LENGTH_SHORT).show()
            }
        })

        // 按钮2: 打开应用列表 (多种尝试)
        btnApps!!.setOnClickListener(View.OnClickListener { v: View? -> openAppList() })

        // 按钮3：打开工程模式
        btnMegaEngineeringMode!!.setOnClickListener(View.OnClickListener { v: View? -> openTargetApp() })
    }

    private fun openAppList() {
        val pm = getPackageManager()

        // 方法1: 尝试打开系统应用管理 (兼容性因厂商而异)
        var intent: Intent = Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS)
        if (intent.resolveActivity(pm) != null) {
            startActivity(intent)
            return
        }

        // 方法2: 打开应用设置总入口
        intent = Intent(Settings.ACTION_APPLICATION_SETTINGS)
        if (intent.resolveActivity(pm) != null) {
            startActivity(intent)
            return
        }

        // 所有方法都失败
        Toast.makeText(this, "抱歉，无法打开应用列表", Toast.LENGTH_LONG).show()
    }

    private fun openTargetApp() {
        // 1. 通过包名获取目标APP的启动意图（主界面）
        val intent = packageManager.getLaunchIntentForPackage(targetPackageName)
            ?: run {
                // 若意图为null，说明设备未安装该APP
                Toast.makeText(this, "未安装包名为 $targetPackageName 的应用", Toast.LENGTH_LONG).show()
                return
            }

        // 2. 可选：添加启动标志（确保在新任务栈中启动，避免与当前APP混淆）
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        // 3. 启动目标APP
        startActivity(intent)
    }
}